﻿using System;
using System.Collections;
using System.ComponentModel;
using System.CodeDom;
using System.CodeDom.Compiler;
using Microsoft.JScript;
using System.Reflection;

namespace XLB.ExtensionMethod
{
    /// <summary>
    /// 
    /// </summary>
    public static class EvalMethod
    {
        /// <summary>
        /// 初始化加载程序的字符串；
        /// </summary>
        public static readonly String _jsClass = @"class theEval{ public function Eval(str:String):String {return eval(str)}}";
        
        /// <summary>
        /// 定义对象
        /// </summary>
        public static object _evalObject = null;

        /// <summary>
        /// 
        /// </summary>
        public static Type _evalType = null;

        //构造函数
         static EvalMethod()
        {
            CodeDomProvider _provider = new JScriptCodeProvider();
            ICodeCompiler _iCode = _provider.CreateCompiler();
            CompilerParameters _parameter = new CompilerParameters();
            _parameter.GenerateInMemory = true;
            CompilerResults _result;
            _result = _iCode.CompileAssemblyFromSource(_parameter, _jsClass);

            Assembly _assembly = _result.CompiledAssembly;
            _evalType = _assembly.GetType("theEval");
            _evalObject = Activator.CreateInstance(_evalType);
        }


        /// <summary>
        /// 把字符串当代码执行
        /// </summary>
        /// <param name="str"></param>
        /// <remarks>调用示例："1+1*2-3/2".Eval()</remarks>
        /// <returns></returns>
        public static object Eval(this string str)
        {
            return _evalType.InvokeMember("Eval", BindingFlags.InvokeMethod, null, _evalObject, new object[] { str });
        }
    }
}
